package ThreadDemo;

import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-29
 * Time: 19:00
 */
//信号量Semaphore简单使用
public class semaphoreTest {
    public static void main(String[] args) {
        Semaphore sem = new Semaphore(1);
        Thread t1 = new Thread(() -> {
            try {
                System.out.println("t1尝试申请资源");
                sem.acquire();
                System.out.println("t1申请资源成功");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                System.out.println("t2尝试申请资源");
                sem.acquire();
                System.out.println("t2申请资源成功");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        t2.start();
    }
    public static void main1(String[] args) throws InterruptedException {
        //信号量用来描述可用资源个数
        Semaphore sem = new Semaphore(3);

        //P - 申请资源+1 V - 释放资源-1
        sem.acquire(2);
        System.out.println("申请两次资源");
        sem.acquire();
        System.out.println("申请一次资源");
        sem.release(2);
        System.out.println("释放两次资源");
        sem.acquire();
        System.out.println("申请一次资源");
        sem.acquire();
        System.out.println("申请一次资源");
        System.out.println("hello");
        //当资源数为零时，再次申请资源就会阻塞等待到释放资源
    }
}
